import scriptLoad from './script-load'
import loadOnce from '@/modules/corejs/load-once/index'
import Vue from 'vue'

declare global {
  interface ArticleData {
    outline: MenuTreeItem[]
    content: string
  }
  interface TypeMenuItem {
    name: string,
    list: MenuTreeItem[]
  }
  interface MenuTreeItem {
    name: string
    id: string
    level: number
    children: MenuTreeItem[]
  }
  interface SearchResultItem {
    id: string
    name: string
    content: string
    path: string
    highlightPath: string
  }
  function algoliasearch (k: string, k2: string): Client
}
interface Client {
  initIndex: (params:string) => number
  // function initIndex (params:string): number
}

export default {
  loadedAlgolia: false,
  getTypeMenuList () {
    return new Promise((resolve: (v: TypeMenuItem[]) => void, reject) => {
      Vue.prototype.$loading.show()
      window.cb_typeMenuList = function (data: any) {
        Vue.prototype.$loading.hide()
        resolve(data)
        delete window.cb_typeMenuList
      }
      scriptLoad('./data/typeMenuList.js')
    })
  },
  getMenuTreeList (type: string) {
    return new Promise((resolve: (v: ArticleData) => void, reject) => {
      Vue.prototype.$loading.show()
      let cbName: string = 'cb_' + type
      window[cbName] = function (data: any) {
        Vue.prototype.$loading.hide()
        resolve(data)
        delete window[cbName]
      }
      scriptLoad('./data/' + encodeURIComponent(type) + '.js')
    })
  },
  async loadAlgolia () {
    if (this.loadedAlgolia) return
    return loadOnce(['https://cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js']).then(() => {
      if (!this.loadedAlgolia) {
        this.loadedAlgolia = true
        let client = algoliasearch('AB8PXP326N', '414792795252da68e2e81916389d28c6')
        window.index = client.initIndex('docs')
      }
    })
  },
  async search (kw: string, page: number) {
    await this.loadAlgolia()
    // return new Promise((resolve, reject) => {
    //   window.index.search(kw, {
    //     'hitsPerPage': 10,
    //     page,
    //     'analytics': false,
    //     'attributesToRetrieve': '*',
    //     'getRankingInfo': true,
    //     'responseFields': '*',
    //     'facets': '*,'
    //   }, (err: any, content: any) => {
    //     console.log(content.hits)
    //     if (err) reject(err)
    //     else resolve(content.hits)
    //   })
    // })
    return window.index.search(kw, {
      'hitsPerPage': 10,
      page,
      'analytics': false,
      'attributesToRetrieve': '*',
      'getRankingInfo': true,
      'responseFields': '*',
      'facets': '*,'
    }).then((content: any) => content.hits).then((data: any) => data.map((item: any) => {
      let highlight = item._highlightResult
      return {
        objectID: item.objectID,
        id: item.id,
        name: item.name,
        path: highlight.outline.value,
        content: highlight.content.value
      }
    }))
  }
}
